package com.zfzs.post.modules.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.zfzs.post.model.dto.QuerTypePageDTO;
import com.zfzs.post.model.vo.*;
import com.zfzs.post.modules.merchant.domain.Merchant;
import com.zfzs.post.modules.merchant.repository.MerchantRepository;
import com.zfzs.post.modules.merchant.service.MerchantService;
import com.zfzs.post.modules.merchant.service.dto.MerchantQueryCriteria;
import com.zfzs.post.modules.merchant.service.mapper.MerchantMapper;
import com.zfzs.post.page.JpaPageHelper;
import com.zfzs.post.utils.PageUtil;
import com.zfzs.post.utils.QueryHelp;
import com.zfzs.post.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 商户信息
 *
 * @author ck
 * @date 2019-09-25
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public Object queryAll(MerchantQueryCriteria criteria, Pageable pageable) {
        Page<Merchant> page = merchantRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(merchantMapper::toDto));
    }

    @Override
    public Object queryAll(MerchantQueryCriteria criteria) {
        return merchantRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
    }

    @Override
    public Merchant findById(Long id) {
        Optional<Merchant> merchant = merchantRepository.findById(id);
        ValidationUtil.isNull(merchant, "Merchant", "id", id);
        return merchant.get();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Merchant create(Merchant resources) {
        resources.setCreateDate(new Timestamp(System.currentTimeMillis()));
        resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return merchantRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Merchant resources) {
        Optional<Merchant> optionalMerchant = merchantRepository.findById(resources.getId());
        ValidationUtil.isNull(optionalMerchant, "Merchant", "id", resources.getId());
        Merchant merchant = optionalMerchant.get();
        merchant.copy(resources);
        merchantRepository.save(merchant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        merchantRepository.deleteById(id);
    }

    @Override
    public int countMerchant(Long id) {
        return merchantRepository.merchantCount(id);
    }

    @Override
    public int silenceMerchant(Long id) {
        return merchantRepository.silenceMerchantCount(id);
    }

    @Override
    public int highMerchant(Long id) {
        return merchantRepository.highMerchantCount(id);
    }

    @Override
    public List<QueryTranTopTenVO> queryTranTopTenList(Long id,String startDate,String endDate) {
        List<Map<String, Object>> list = merchantRepository.queryTranTopTenList(id,startDate,endDate);
        List<QueryTranTopTenVO> collect = list.stream()
                .map(e -> {
                    QueryTranTopTenVO agent = JSON.parseObject(JSON.toJSONString(e), QueryTranTopTenVO.class);
                    return agent;
                }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public int queryCountByAgentIds(List<Long> ids, String startDate, String endDate) {
        return merchantRepository.queryCountByAgentIds(ids, startDate, endDate);
    }

    @Override
    public List<QueryAddMerchantInfoListVO> queryAddMerchantInfoList(List<Long> ids, String startDate, String endDate, Long terminalTypeId) {
        List<Map<String, Object>> list = merchantRepository.queryAddMerchantInfoList(ids, startDate, endDate, terminalTypeId);
        List<QueryAddMerchantInfoListVO> collect = list.stream()
                .map(e -> {
                    QueryAddMerchantInfoListVO agent = JSON.parseObject(JSON.toJSONString(e), QueryAddMerchantInfoListVO.class);
                    return agent;
                }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public int queryAddMerchantCount(List<Long> ids, String startDate, String endDate, Long terminalTypeId) {
        return merchantRepository.queryAddMerchantCount(ids, startDate, endDate, terminalTypeId);
    }

    @Override
    public JpaPageHelper queryAddMerchantList(QuerTypePageDTO dto) {
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        Long channelId = dto.getChannelId();
        String endDate = dto.getEndDate();
        List<Long> ids = dto.getIds();
        String startDate = dto.getStartDate();
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);//借助计算起始位置
        // 计算数据总条数
        Integer total = merchantRepository.queryAddMerchantListCount(channelId, ids, startDate, endDate);
        if (total == null) {
            total = 0;
        }
        List<Map<String, Object>> list = merchantRepository.queryAddMerchantList(channelId, ids, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
        List<QueryAddMerchantListVO> collect = list.stream()
                .map(e -> {
                    QueryAddMerchantListVO agent = JSON.parseObject(JSON.toJSONString(e), QueryAddMerchantListVO.class);
                    return agent;
                }).collect(Collectors.toList());

        JpaPageHelper<QueryAddMerchantListVO> page = new JpaPageHelper<>(list, pageSize, pageNum, total);
        // 转换分页数据
        for (int i = 0; i < collect.size(); i++) {
            Long terminalTypeId = collect.get(i).getTerminalTypeId();
            int count = queryAddMerchantCount(ids, startDate, endDate, terminalTypeId);
            collect.get(i).setCount(count);
        }
        page.setResult(collect);
        return page;
    }

    @Override
    public int queryTotalTerminalCount(List<Long> ids, String startDate, String endDate) {
        return merchantRepository.queryTotalTerminalCount(ids, startDate, endDate);
    }

    @Override
    public Merchant findBySn(String sn) {
        return merchantRepository.findBySn(sn);
    }

}